package com.mazihao.emos.task;

import com.mazihao.emos.config.shiro.JwtUtil;
import com.mazihao.emos.db.pojo.MessageEntity;
import com.mazihao.emos.db.pojo.MessageRefEntity;
import com.mazihao.emos.db.pojo.TbMessage;
import com.mazihao.emos.db.pojo.TbMessageRef;
import com.mazihao.emos.exception.EmosException;
import com.mazihao.emos.service.MessageService;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mazihao
 */
@Component
@Slf4j
public class MessageTask {

    @Resource
    private ConnectionFactory factory;

    @Resource
    private MessageService messageService;
    @Autowired
    private JwtUtil jwtUtil;

    public void send(String topic, TbMessage entity) {
        messageService.insertMessage(entity);
    }

    @Async
    public void sendAsync(String topic, TbMessage entity) {
        this.send(topic, entity);
    }

    /**
     * 接收消息
     * @param topic 就是userId
     * @return
     */
    public int receive(int topic) {
        int count = 0;
        List<TbMessage> list = messageService.searchMessageByPage(topic);
        for (TbMessage message : list) {
            String messageId = message.getId();
            TbMessageRef ref = messageService.searchMessageRefByMessageId(messageId, topic);
            if (ref == null) {
                TbMessageRef entity = new TbMessageRef();
                entity.setMessageId(message.getId());
                entity.setReceiverId(topic);
                entity.setReadFlag(false);
                entity.setLastFlag(true);
                messageService.insertRef(entity);
                count++;
            }
        }
        return count;
    }


    @Async
    public void receiveAsync(int topic){
        this.receive(topic);
    }

    public void deleteQueue(String topic) {
        try (Connection connection = factory.newConnection();
         Channel channel = connection.createChannel()){
            channel.queueDelete(topic);
            log.debug("队列[{}]已被删除", topic);
        } catch (Exception e) {
            log.error("删除队列[{}]失败", topic, e);
            throw new EmosException("删除队列失败");
        }
    }

    @Async
    public void deleteQueueAsync(String topic) {
        this.deleteQueue(topic);
    }
}
